﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using Microsoft.Isam.Esent.Collections.Generic;
using System.IO;
using System.Configuration;

namespace Tapestry.Web.Storage
{
    public class PersistentStorage:ConcurrentDictionary<Url, Uri>,IPersistentStorage
    {
        PersistentDictionary<string, Uri> persistentStore;

        public String Path
        {
            get { return ConfigurationManager.AppSettings["Tapestry.Web.Storage.UriStore"]; }
        }

        public PersistentStorage()
        {
            persistentStore = new PersistentDictionary<string, Uri>(Path);
        }
        
        void IDictionary<Url, Uri>.Add(Url key, Uri value)
        {
            this[key] = value;
        }

        bool IDictionary<Url, Uri>.Remove(Url key)
        {
           Uri value;
           if (base.TryRemove(key, out value))
           {
               persistentStore.Remove(key.ToString());
               return true;
           }
           return false;  
        }

        void ICollection<KeyValuePair<Url, Uri>>.Add(KeyValuePair<Url, Uri> item)
        {
            this[item.Key] = item.Value;
        }

        void ICollection<KeyValuePair<Url, Uri>>.Clear()
        {
            persistentStore.Clear();
            base.Clear();
        }

        bool ICollection<KeyValuePair<Url, Uri>>.Remove(KeyValuePair<Url, Uri> item)
        {
            Uri value;
            if (base.TryRemove(item.Key, out value))
            {
                persistentStore.Remove(item.Key.ToString());
                return true;
            }
            return false;  
        }

        bool IDictionary<Url, Uri>.ContainsKey(Url key)
        {
            bool contains = this.ContainsKey(key);
            if (!contains)
            {
                contains = persistentStore.ContainsKey(key);
            }
            return contains;
        }
       
        Uri IDictionary<Url, Uri>.this[Url key]
        {
            get
            {
                Uri uri = null;
                if (this.ContainsKey(key))
                {
                    uri = base[key];
                }
                else
                {
                    if (persistentStore.TryGetValue(key, out uri))
                    {
                        base[key] = uri;
                    }
                    
                }
                return uri;
            }
            set
            {
                base[key] = value;
                persistentStore[key] = value;
                //persistentStore.Add(new KeyValuePair<string, Uri>(key.ToString(), value));
            }
        }

        public void Dispose()
        {
            persistentStore.Dispose();
        }
    }
}
